import { RedisService } from '@/redis/redis.service'
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { createTransport, Transporter } from 'nodemailer'

@Injectable()
export class EmailService {
  transporter: Transporter

  constructor(private readonly redisService: RedisService, private configService: ConfigService) {
    this.transporter = createTransport({
      host: 'smtp.qq.com',
      port: 587,
      secure: false,
      auth: {
        user: configService.get('EMAIL_USER'),
        pass: configService.get('EMAIL_PASSWORD'),
      },
    })
  }

  async sendEmailCode(address: string) {
    const code = Math.random().toString().slice(2, 8)

    await this.redisService.set(`captcha_${address}`, code, 5 * 60)

    await this.sendMail({
      to: address,
      subject: '获取验证码',
      html: `<p>你的验证码为:<br>
              <span style="color: blue;font-size:28px;">${code}</span>
            </p>`,
    })
    return '发送成功'
  }

  async sendMail({ to, subject, html }) {
    await this.transporter.sendMail({
      from: {
        name: `${this.configService.get('WEB_NAME')}验证码`,
        address: this.configService.get('EMAIL_USER'),
      },
      to,
      subject,
      html,
    })
  }
}
